package com.activiti.spring.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipInputStream;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.activiti.spring.entity.Employee;

@RestController
public class EmployeeController {
	@Autowired
	private RepositoryService repositoryService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	
	@GetMapping("getEmployee")
	@ResponseBody
	public Employee getEmployee() {
		Employee entity = new Employee();
		entity.setId(1);
		entity.setName("张三丰");
		return entity;
	}

	/**
	 * 类路径下
	 * @return
	 */
	@GetMapping("getDeploy")
	@ResponseBody
	public Deployment setProcess() {
		Deployment deploy = repositoryService.createDeployment().name("请假流程")
				.addClasspathResource("diagrams/HelloWorld.bpmn").deploy();
		System.out.println("部署id:" + deploy.getId());
		System.out.println("部署名称：" + deploy.getName());
		return deploy;
	}
	
	
	/**
	 * 
	 * zip文件上传
	 * @return
	 * @throws IOException 
	 */
	@GetMapping("setZipProcess")
	@ResponseBody
	public Deployment setZipProcess() throws IOException {
		InputStream is=this.getClass().getClassLoader().getResourceAsStream("diagrams/HelloWorld.zip");
		ZipInputStream zip=new ZipInputStream(is);
		Deployment deploy=repositoryService
				.createDeployment()
				.name("zip部署请假流程")
				.addZipInputStream(zip)
				.deploy();
		is.close();
		zip.close();
		return deploy;
	}
	
	/**
	 * 删除流程定义
	 * @param deploymentId
	 * @return
	 */
	@GetMapping("deleteProcessDefinition")
	@ResponseBody
	public String deleteProcessDefinition(@RequestParam("deploymentId")String deploymentId){
		repositoryService
		//.deleteDeployment(deploymentId);//只能删除没有启动的流程，如果流程启动抛出PersistenceException
		.deleteDeployment(deploymentId, true);//不管是否启动级联删除
		return "success";
	}
	
	@GetMapping("pageDeployment")
	@ResponseBody
	public String pageDeployment(@RequestParam("firstResult") Integer firstResult,@RequestParam("maxResults") Integer maxResults){
		List<ProcessDefinition> result= repositoryService.createProcessDefinitionQuery()
		.orderByProcessDefinitionKey().desc()
		.listPage(firstResult, maxResults);
		for(ProcessDefinition pd: result){
			System.out.println(pd.getDeploymentId());
			System.out.println(pd.getDescription());
			System.out.println(pd.getName());
		}
		System.out.println("=========="+result.size());
		return "success";
	}
	
	/**
	 * 启动流程实例
	 * @param model
	 * @param processKey
	 * @return
	 */
	@GetMapping("getProcessEngine")
	@ResponseBody
	public String getProcessEngine(Model model,@RequestParam("processKey") String processKey){
		ProcessInstance pi=runtimeService.startProcessInstanceByKey(processKey);//对应pbmn中的id
		
	
		System.out.println("流程实例id:"+pi.getId());
		System.out.println("流程定义id："+pi.getProcessDefinitionId());
		return "success";
	}
	
	@GetMapping("taskService")
	@ResponseBody
	public String getTaskService(Model model,@RequestParam("assignee") String assignee){
		List<Task> tasks=taskService.createTaskQuery().taskAssignee(assignee).list();//对应pbmn中的id
		for(Task task: tasks){
			System.out.println(task.getAssignee());
			System.out.println(task.getId());
			System.out.println(task.getName());
			System.out.println(task.getCreateTime());
			System.out.println(task.getProcessInstanceId());
			System.out.println(task.getExecutionId());
		}
		return "success";
	}

	/**
	 * 执行任务
	 * @param model
	 * @param taskId
	 * @return
	 */
	@GetMapping("completeMyProcess")
	@ResponseBody
	public String completeMyProcess(Model model,@RequestParam("taskId") String taskId){
		taskService.complete(taskId);
		return taskId;
	}
	
	
	/**
	 * 设置流程参数（任务）
	 * 属性值可以是javaBean对象（被序列化的），存的序列化对象类添加了属性，需要为类添加序列化版本号
	 * @param taskId
	 * @return
	 */
	@GetMapping("setProcessVariable")
	@ResponseBody
	public String setProcessVariable(@RequestParam("taskId") String taskId){
//		runtimeService.setVariable(executionId, variableName, value);通过流程id设置流程参数
		taskService.setVariableLocal(taskId, "请假天数", 3);//设置流程参数，taskId执行id,在`act_ru_variable` 表TASK_ID有记录，该流程task执行完，该参数删除
		taskService.setVariable(taskId, "请假开始时间", new Date());
		taskService.setVariable(taskId, "请假事由", "回家探亲");
		return taskId;
	}
	
	/**
	 * 
	 * 获取流程参数
	 * @param taskId
	 * @param variableName
	 * @return
	 */
	@GetMapping("getProcessVariable")
	@ResponseBody
	public String getProcessVariable(@RequestParam("taskId") String taskId,@RequestParam("variableName") String variableName){
//		runtimeService.getVariable(executionId, variableName);//获取流程所有的流程参数
		taskService.getVariable(taskId, variableName);
		return "success";
	}
	
	@GetMapping("getPng")
	@ResponseBody
	public void getPng(@RequestParam("deploymentId") String deploymentId) throws IOException{
		
		List<String> names= repositoryService.getDeploymentResourceNames(deploymentId);
		String resourceName="";
		if(names!=null&&names.size()>0){
			for(String name:names){
				if(name.indexOf(".png")>0)
					resourceName=name;
			}
		}
		InputStream in=repositoryService.getResourceAsStream(deploymentId, resourceName);
		
		FileOutputStream out=new FileOutputStream(new File("D:\\hellowored.png"));
		byte[] b=new byte[1024];
		while(in.read(b)!=-1){
			out.write(b);
		}
		System.out.println(in.read());
		in.close();
		out.close();

	}
}
